package mapreduceSort;

import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class Sort {
	public static class Map extends Mapper<Object, Text, IntWritable, IntWritable> {
		private static IntWritable data = new IntWritable();

		public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
			String line = value.toString();
			if("".equals(line)){
				
			}else{
				data.set(Integer.valueOf(line));
			}
			
			context.write(data, new IntWritable(1));
		}

	}

	public static class Reduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
		private static IntWritable linenum = new IntWritable(1);

		public void reduce(IntWritable key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			for (IntWritable val : values) {
				context.write(linenum, key);
				linenum = new IntWritable(linenum.get() + 1);
			}
		}

	}

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Configuration conf = new Configuration();
		conf.set("mapred.job.tracker", "192.168.8.70:8020");
		String[] idArgs = new String[] { "hdfs://192.168.8.70:8020/tmp/wordCount/sort_in", "hdfs://192.168.8.70:8020/tmp/wordCount/sort_out" };
		String[] otherArgs = new GenericOptionsParser(conf, idArgs).getRemainingArgs();
		if (otherArgs.length != 2) {
			System.err.println("Usage:data sort <int> <out>");
			System.exit(2);
		}

		Job job = new Job(conf, "Data Sort");
		job.setJarByClass(Sort.class);

		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);

		job.setOutputKeyClass(IntWritable.class);
		job.setOutputValueClass(IntWritable.class);

		FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
		uriExistAndDelete(conf);
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);

	}
	
	private static void uriExistAndDelete(Configuration conf) throws IOException {
		String uri="hdfs://192.168.8.70:8020";
		FileSystem fs=FileSystem.get(URI.create(uri),conf);
		String s="/tmp/wordCount/sort_out";
		Path p=new Path(s);
		Boolean a=fs.delete(p, true);
		System.out.println(a);
	}
}
